'''
https://leetcode.cn/problems/sum-root-to-leaf-numbers/?envType=study-plan-v2&envId=top-interview-150
'''
from typing import Optional


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def sumNumbers(self, root: Optional[TreeNode]) -> int:
        def f(root, pre):
            if not root.left and not root.right:
                return pre * 10 + root.val
            cur = pre * 10 + root.val
            res = 0
            res += f(root.left, cur) if root.left else 0
            res += f(root.right, cur) if root.right else 0
            return res
        return f(root, 0)
